<template>
  <div class="address-container">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" size="20" />
      </div>
      <div class="header-title">收货地址</div>
    </div>

    <!-- 添加地址按钮 -->
    <div class="add-address-button-top">
      <van-button type="primary" block icon="plus" @click="handleAddAddress">
        添加新地址
      </van-button>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" color="var(--primary-color)" />
      </div>
      <div v-else-if="addresses.length > 0">
        <div v-for="address in addresses" :key="address.id" class="address-item">
          <div class="address-content">
            <div class="address-info">
              <div class="contact-info">
                <span class="name">{{ address.name }}</span>
                <span class="phone">{{ address.phone }}</span>
                <van-tag v-if="address.isDefault === '1'" type="primary" round size="mini" class="default-tag">默认</van-tag>
              </div>
              <div class="address-detail">{{ address.province }} {{ address.city }} {{ address.district }} {{
                address.address }}</div>
            </div>
            <div class="address-actions">
              <div class="action-button" @click="handleEditAddress(address)">
                <van-icon name="edit" class="edit-icon" />
              </div>
              <div class="action-button" @click="handleDeleteAddress(address.id)">
                <van-icon name="delete" class="delete-icon" />
              </div>
            </div>
          </div>
          <div class="address-footer" v-if="address.isDefault === '0'">
            <div class="default-button" @click="setDefaultAddress(address.id)">
              设为默认地址
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <van-icon name="location-o" size="48" class="empty-icon" />
        <p class="empty-text">暂无收货地址</p>
        <p class="empty-subtext">点击上方按钮添加新地址</p>
      </div>
    </div>

    <!-- 地址表单弹窗 -->
    <van-popup v-model:show="addressDialogOpen" position="bottom" round closeable :style="{ height: '90%' }">
      <div class="form-header">
        <div class="form-title">{{ currentAddress && currentAddress.id ? '编辑地址' : '添加新地址' }}</div>
        <div class="form-subtitle">请填写收货地址信息，带 * 的为必填项</div>
      </div>

      <div class="address-form">
        <van-form @submit="handleSaveAddress">
          <van-cell-group inset>
            <van-field v-model="formData.name" name="name" label="收货人 *" placeholder="请输入收货人姓名"
              :rules="[{ required: true, message: '请填写收货人姓名' }]" />

            <van-field v-model="formData.phone" name="phone" label="手机号 *" placeholder="请输入手机号码" :rules="[
              { required: true, message: '请填写手机号码' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误' }
            ]" />

            <van-field v-model="formData.province" name="province" label="省份 *" placeholder="请输入省份"
              :rules="[{ required: true, message: '请填写省份' }]" />

            <van-field v-model="formData.city" name="city" label="城市 *" placeholder="请输入城市"
              :rules="[{ required: true, message: '请填写城市' }]" />

            <van-field v-model="formData.district" name="district" label="区县 *" placeholder="请输入区县"
              :rules="[{ required: true, message: '请填写区县' }]" />

            <van-field v-model="formData.address" name="address" label="详细地址 *" type="textarea" rows="2" autosize
              placeholder="请输入详细地址" :rules="[{ required: true, message: '请填写详细地址' }]" />

            <div class="default-switch-container">
              <van-switch v-model="formData.isDefault" size="24" class="default-switch" />
              <span class="default-label">设为默认地址</span>
            </div>
          </van-cell-group>

          <div class="form-actions">
            <van-button round block type="primary" native-type="submit">
              保存
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 删除确认弹窗 -->
    <van-dialog v-model:show="deleteDialogOpen" title="确认删除" show-cancel-button confirm-button-text="删除"
      confirm-button-color="#ee0a24" @confirm="confirmDeleteAddress">
      <div class="delete-confirm-content">
        您确定要删除这个收货地址吗？此操作无法撤销。
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { getAddressList, addAddress, updateAddress, deleteAddress, setDefaultAddress as setDefault } from '@/api/address'

const router = useRouter()
const addressDialogOpen = ref(false)
const deleteDialogOpen = ref(false)
const addressToDelete = ref(null)
const currentAddress = ref(null)

// 地址列表
const addresses = ref([])
const loading = ref(false)

// 获取地址列表
const fetchAddressList = async () => {
  loading.value = true
  try {
    const response = await getAddressList()
    if (response && response.code === 0 && response.data.list) {
      addresses.value = response.data.list
    } else {
      showToast(response?.message || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表失败', error)
    showToast('获取地址列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取地址列表
onMounted(() => {
  fetchAddressList()
})

// 表单数据
const formData = ref({
  id: '',
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  isDefault: false
})

// 监听currentAddress变化，更新表单数据
watch(currentAddress, (newVal) => {
  if (newVal) {
    formData.value = { 
      ...newVal,
      // 将字符串转换为布尔值供van-switch使用
      isDefault: newVal.isDefault === '1' || newVal.isDefault === 1
    }
  }
})

// 导航方法
const goBack = () => {
  router.back()
}

// 添加地址
const handleAddAddress = () => {
  currentAddress.value = {
    id: '',
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    address: '',
    isDefault: false
  }
  addressDialogOpen.value = true
}

// 编辑地址
const handleEditAddress = (address) => {
  currentAddress.value = address
  addressDialogOpen.value = true
}

// 删除地址
const handleDeleteAddress = (id) => {
  addressToDelete.value = id
  deleteDialogOpen.value = true
}

// 确认删除
const confirmDeleteAddress = async () => {
  if (addressToDelete.value) {
    showLoadingToast({
      message: '删除中...',
      forbidClick: true,
    })

    try {
      const response = await deleteAddress(addressToDelete.value)
      if (response && response.code === 0) {
        // 删除成功后重新获取列表
        await fetchAddressList()
        showToast('删除成功')
      } else {
        showToast(response?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除地址失败', error)
      showToast('删除失败')
    } finally {
      closeToast()
      addressToDelete.value = null
    }
  }
}

// 保存地址
const handleSaveAddress = async () => {
  showLoadingToast({
    message: '保存中...',
    forbidClick: true,
  })

  try {
    let response
    // 准备提交的数据，将布尔值转换为字符串
    const submitData = {
      ...formData.value,
      isDefault: formData.value.isDefault ? '1' : '0'
    }
    
    if (submitData.id) {
      // 更新现有地址
      response = await updateAddress(submitData)
    } else {
      // 添加新地址
      submitData.id = 0
      response = await addAddress(submitData)
    }

    if (response && response.code === 0) {
      // 保存成功后重新获取列表
      await fetchAddressList()
      showToast('保存成功')
      addressDialogOpen.value = false
      currentAddress.value = null
    } else {
      showToast(response?.message || '保存失败')
    }
  } catch (error) {
    console.error('保存地址失败', error)
    showToast('保存失败')
  } finally {
    closeToast()
  }
}

// 设置默认地址
const setDefaultAddress = async (id) => {
  showLoadingToast({
    message: '设置中...',
    forbidClick: true,
  })

  try {
    const response = await setDefault(id)
    if (response && response.code === 0) {
      // 设置成功后重新获取列表
      await fetchAddressList()
      showToast('已设为默认地址')
    } else {
      showToast(response?.message || '设置失败')
    }
  } catch (error) {
    console.error('设置默认地址失败', error)
    showToast('设置失败')
  } finally {
    closeToast()
  }
}
</script>

<style scoped>
.address-container {
  min-height: 100vh;
  background-color: white;
  padding-bottom: 80px;
}

/* 顶部导航 */
.nav-header {
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  height: 48px;
  background-color: white;
  z-index: 20;
  padding: 0 16px;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 16px;
}

.back-button {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  flex: 1;
}

/* 添加地址按钮 */
.add-address-button-top {
  padding: 0 16px;
  margin-bottom: 16px;
}

.add-address-button-top :deep(.van-button) {
  background-color: #2563eb;
  border-color: #2563eb;
}

.add-address-button-top :deep(.van-button:active) {
  background-color: #1d4ed8;
  border-color: #1d4ed8;
}

/* 地址列表 */
.address-list {
  padding: 0 16px;
}

.address-item {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  border: none;
}

.address-content {
  display: flex;
  padding: 16px;
}

.address-info {
  flex: 1;
}

.contact-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  margin-right: 12px;
}

.phone {
  font-size: 14px;
  color: #4b5563;
}

.default-tag {
  margin-left: 8px;
  background-color: #dbeafe;
  color: #2563eb;
  border: none;
}

.address-detail {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  align-items: flex-start;
}

.action-button {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  cursor: pointer;
}

.action-button:hover {
  background-color: #f9fafb;
}

.edit-icon,
.delete-icon {
  font-size: 18px;
  color: #6b7280;
}

.address-footer {
  padding: 12px 16px;
  border-top: 1px solid #f3f4f6;
}

.default-button {
  color: #2563eb;
  font-size: 14px;
  cursor: pointer;
}

.default-button:hover {
  color: #1d4ed8;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
}

.empty-icon {
  color: #d1d5db;
}

.empty-text {
  margin-top: 16px;
  font-size: 16px;
  color: #6b7280;
}

.empty-subtext {
  margin-top: 8px;
  font-size: 14px;
  color: #9ca3af;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 0;
}

/* 表单样式 */
.form-header {
  padding: 16px;
  text-align: center;
  border-bottom: 1px solid #f3f4f6;
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.form-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin-top: 4px;
}

.address-form {
  padding: 16px;
}

/* Add borders to input fields */
.address-form :deep(.van-field__control) {
  border: 1px solid #d1d5db;
  border-radius: 4px;
  padding: 8px 12px;
  background-color: #f9fafb;
}

.address-form :deep(.van-field__control:focus) {
  border-color: #2563eb;
  box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
  outline: none;
}

.address-form :deep(.van-cell) {
  padding: 16px 0;
}

.address-form :deep(.van-field__label) {
  width: 90px;
  color: #374151;
  font-weight: 500;
}

.default-switch-container {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: white;
  border-top: 1px solid #f3f4f6;
  margin-top: 16px;
}

.default-switch {
  margin-right: 12px;
}

.default-switch :deep(.van-switch--checked) {
  background-color: #2563eb;
}

.default-label {
  font-size: 14px;
  color: #1f2937;
}

.form-actions {
  margin-top: 24px;
  padding: 0 16px;
}

.form-actions :deep(.van-button) {
  background-color: #2563eb;
  border-color: #2563eb;
}

.form-actions :deep(.van-button:active) {
  background-color: #1d4ed8;
  border-color: #1d4ed8;
}

/* 删除确认弹窗 */
.delete-confirm-content {
  padding: 24px 16px;
  text-align: center;
  color: #1f2937;
}
</style>